#!/bin/bash

# Check if the correct number of arguments is provided
if [ "$#" -ne 2 ]; then
  echo "Usage: $0 BASE_DIR DEST_DIR"
  exit 1
fi

# Input arguments
BASE_DIR=$1
DEST_DIR=$2

# Ensure BASE_DIR exists
if [ ! -d "$BASE_DIR" ]; then
  echo "Error: BASE_DIR '$BASE_DIR' does not exist."
  exit 1
fi

# Create DEST_DIR if it doesn't exist
mkdir -p "$DEST_DIR"

# Iterate over all subdirectories in BASE_DIR
for SRC_DIR in "$BASE_DIR"/*; do
  if [ -d "$SRC_DIR" ]; then
    # Process subdirectories within each source directory
    for SUB_DIR in "$SRC_DIR"/*; do
      if [ -d "$SUB_DIR" ]; then
        # Get the relative path of the subdirectory
        RELATIVE_PATH="${SUB_DIR#$SRC_DIR/}" # Strip SRC_DIR prefix
        DEST_SUB_DIR="$DEST_DIR/$RELATIVE_PATH"

        # Create the corresponding destination subdirectory
        mkdir -p "$DEST_SUB_DIR"

        # Copy files from the source subdirectory to the destination subdirectory
        for FILE in "$SUB_DIR"/*; do
          if [ -f "$FILE" ]; then
            FILENAME=$(basename "$FILE")
            DEST_FILE="$DEST_SUB_DIR/$FILENAME"
            COUNTER=1

            # Avoid overwriting by appending a numeric suffix if the file already exists
            while [ -e "$DEST_FILE" ]; do
              DEST_FILE="$DEST_SUB_DIR/${FILENAME%.*}_$COUNTER.${FILENAME##*.}"
              ((COUNTER++))
            done

            # Copy the file to the destination
            cp "$FILE" "$DEST_FILE"
          fi
        done
      fi
    done
  fi
done

echo "Merge complete. Files from '$BASE_DIR' have been merged into '$DEST_DIR'."
